import { pickedFaceData } from '@amcax/base';
import { RJSFSchema } from '@rjsf/utils';
import { useEffect, useState } from 'react';
import { PickInputRJSFFormat } from '../../../../../../common/components/command-form/constants';
import { PickableCommandForm } from '../../../../../../common/components/command-form/pickable';
import { useCommand } from '../../../../../../common/hooks/useCommand';
import { useTools } from '../../../../../../common/hooks/useTools';
import { FeaturedCmdDialogParams } from '../../../../../../types';

type Params = {
  base: string;
  faces: string[];
};

interface FaceCommandProps {
  cmdID: string;
  cmdName: string;
  facesPlaceholder: string;
}

export function CmdFace({
  title,
  onClose,
  props,
  cmdID,
  cmdName,
  facesPlaceholder,
}: FeaturedCmdDialogParams & FaceCommandProps) {
  const [faces, setFaces] = useState<pickedFaceData[]>([]);

  const schema: RJSFSchema = {
    type: 'array',
    items: {
      type: 'string',
      enum: [],
    },
    format: PickInputRJSFFormat.MultiPickFace,
    uniqueItems: true,
  };

  const { picker } = useTools();

  useEffect(() => {
    preview();
  }, [faces]);

  useEffect(() => {
    if (!props?.params) {
      setFaces([]);
      return () => {};
    }

    const params: Params = props.params;
    const { base, faces } = params;

    const faceIds = faces.map((face) => `${base}:f${face}`);
    initEditDependency(faceIds);

    setFaces(
      faceIds.map(
        (curve) => picker.generatePickObjByPickID(curve) as pickedFaceData,
      ),
    );
  }, [props?.shape]);

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);
    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, clear, isLoading } =
    useCommand(cmdID, {
      commandName: cmdName,
      editDxid: props?.shape,
      dependencies: props?.params ? [props.params.base] : [],
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const execute = (preview: boolean) => {
    return confirmCommand(
      {
        a: {
          faces: faces.map((c) => Number(c.meshId.split(':f')[1])),
          base: faces[0].idInfo.o,
        },
      },
      preview,
    );
  };

  const isFormDataValid = () => {
    return faces.length >= 1 && faces.every((c) => c != null);
  };

  const preview = async () => {
    clear();

    if (!isFormDataValid()) {
      return;
    }

    await execute(true);
  };

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      title={title}
      schema={schema}
      submitLoading={isLoading}
      onChange={(v) => {
        setFaces(v);
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      extraUiSchema={{
        'ui:placeholder': facesPlaceholder,
        'ui:autofocus': true,
      }}
      formData={faces}
      isFormDataValid={isFormDataValid()}
    />
  );
}
